package cn.edu.jmu.oelp.controller;

import cn.edu.jmu.oelp.pojo.Article;
import cn.edu.jmu.oelp.pojo.ReqArticle;
import cn.edu.jmu.oelp.pojo.RespCode;
import cn.edu.jmu.oelp.pojo.RespEntity;
import cn.edu.jmu.oelp.service.ArticleService;
import cn.edu.jmu.oelp.service.ParagraphsService;
import cn.edu.jmu.oelp.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Transactional(rollbackFor = Exception.class)
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ParagraphsService paragraphsService;

    @Autowired
    private TypeService typeService;


    @RequestMapping("/addArticle")
    public RespEntity addArticle(@RequestBody ReqArticle reqArticle) {
        Article article;
        if (reqArticle != null) {
            article = new Article();
            article.setContent(reqArticle.getContent());
            article.setMarkId(reqArticle.getMarkId());
            if (articleService.addArticle(article)&&paragraphsService.splitArticle(article)){
                List<String> typeList = reqArticle.getTypeList();
                for (String t : typeList) {
                    typeService.addType(t,article.getId());
                }
                return new RespEntity(RespCode.SUCCESS, article);
            }
        }
        return new RespEntity(RespCode.WARN);
    }

    @RequestMapping("/delArticle")
    public RespEntity delArticle(@RequestParam("articleId") int articleId) {
        if (articleService.delArticle(articleId)) {
            return new RespEntity(RespCode.SUCCESS);
        } else {
            return new RespEntity(RespCode.WARN);
        }
    }

    @RequestMapping("/updateArticle")
    public RespEntity updateArticle(@RequestBody Article article) {
        if (articleService.updateArticle(article)) {
            return new RespEntity(RespCode.SUCCESS);
        } else {
            return new RespEntity(RespCode.WARN);
        }
    }

    @RequestMapping("/selArticleById")
    public RespEntity selArticleById(@RequestParam("articleId") int articleId) {
        Article article= articleService.selArticleById(articleId);
        System.out.println(article);
        return new RespEntity(RespCode.SUCCESS,article);
    }
}
